package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.atguigu.spzx.manager.mapper.SysRoleMenuMapper;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.manager.service.SysRoleMenuService;
import com.atguigu.spzx.model.dto.system.AssignMenuDto;
import com.atguigu.spzx.model.entity.system.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Long roleId) {

        //查询两部分数据：
        // 查询所有菜单，要求组装父子关系
        List<SysMenu> sysMenuList = sysMenuService.findNodes();   //  业务层 调用 业务层    注意：事务传播行为。

        // 查询这个角色之前拥有的菜单id集合
        List<Long> roleMenuIds = sysRoleMenuMapper.findMenuIdsByRoleId(roleId);

        // 将数据存储到Map中进行返回
        Map<String , Object> result = new HashMap<>() ;
        result.put("sysMenuList" , sysMenuList) ;
        result.put("roleMenuIds" , roleMenuIds) ;

        return result;
    }

    @Override
    public void doAssign(AssignMenuDto assignMenuDto) {
        //1.先删除旧的关系数据
        sysRoleMenuMapper.deleteRelationshipByRoleId(assignMenuDto.getRoleId());

        //2.再保存新的关系数据
        List<Map<String, Number>> menuIdList = assignMenuDto.getMenuIdList();
        if(!CollectionUtils.isEmpty(menuIdList)){
            sysRoleMenuMapper.insertRelationship(assignMenuDto);
        }
    }
}
